# -*- coding: utf-8 -*-
# filename: handle.py

import hashlib
import reply
import receive
import web
import basic
import media
import cv2
import json
# import image_rec
import talk_api
import face_I_konw


class Handle(object):

    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "Hello, What are you nong sha lei ? ? ?"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "madisonLBK"

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print "handle/GET func: hashcode:%s, signature:%s " % (hashcode, signature)
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception, Argument:
            return Argument

    def POST(self):
        try:
            webData = web.data()
            # print "\n\nHandle Post webdata is :\n", webData  #后台打印日志
            recMsg = receive.parse_xml(webData)

            print "from:  %s \t MsgType:  %s" % (recMsg.FromUserName, recMsg.MsgType)

            toUser = recMsg.FromUserName
            fromUser = recMsg.ToUserName
            userid = toUser[0:15]
            if isinstance(recMsg, receive.Msg):

                if recMsg.MsgType == 'text':
                    # content = "text"
                    print "A: ", recMsg.Content
                    content = talk_api.talks_robot(userid, recMsg.Content)
                    print "B: ", content
                    # content = "：)  " + recMsg.Content
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                elif recMsg.MsgType == 'image':

                    try:
                        reply.Msg().send()
                        mediaId = recMsg.MediaId
                        #print "mediaId:", mediaId
                        myMedia = media.Media()
                        accessToken = basic.Basic().get_access_token()
                        #print accessToken
                        image_name = myMedia.get(accessToken, mediaId)
                        #print image_name
                        detectdata = face_I_konw.detectface(image_name)
                        if len(detectdata)<10:
                        	content = '识别失败，要不换个脸大的试试?'
                        else:
	                        content = detectdata.replace('[','').replace(']','').replace('{','').replace('}','')
	                        content = '哇，我看出来了: '+ content.encode("utf-8")
                    except:
                    	content = '识别失败，要不换个脸大的试试?'
                    print content
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                elif recMsg.MsgType == 'voice':
                    if recMsg.Recognition:
                        content = recMsg.Recognition
                        content = talk_api.talks_robot(userid, content)
                    else:
                        content = "未开启语音识别功能或者识别内容为空"
                    print content
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                elif recMsg.MsgType == 'location':

                    location_x = recMsg.Location_X
                    location_y = recMsg.Location_Y
                    content = "您所在的位置：经度" + location_x + "；纬度：" + location_y
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()

                else:
                    return reply.Msg().send()

            elif isinstance(recMsg, receive.EventMsg):
                if recMsg.Event == 'CLICK':
                    if recMsg.Eventkey == 'mpGuide':
                        content = "设备已绑定"
                        print content
                    if recMsg.Eventkey == 'mpGuide_ON':
                        content = "设备已打开"
                        print content
                    if recMsg.Eventkey == 'mpGuide_OFF':
                        content = "设备已关闭"
                        print content
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
            else:
                print "other 暂且不处理\n\n"
                return reply.Msg().send()

        except Exception, Argment:
            return Argment
